<template>
    <div class="container_box">
        <el-scrollbar class="main_box">
            <div class="create_content">
                <!-- 群发标题 -->
                <div class="content-left">
                    <div class="list_item">
                        <div class="item_title">
                            <span class="title_icon"></span><span class="should">*</span>群发标题
                        </div>
                        <div class="item_con">
                            <el-input
                                v-model="form.title"
                                class="item_con_input"
                                placeholder="请输入群发标题"
                                maxlength="50"
                                show-word-limit />
                        </div>
                    </div>
                    <!-- 发送客户范围 -->
                    <div class="list_item mt20">
                        <div class="item_title">
                            <span class="title_icon"></span>
                            选择群主
                            <el-popover
                                placement="top-start"
                                effect="dark"
                                :width="200"
                                trigger="hover"
                                content="每次群发最多发送给每个群主最近活跃的200个群聊，最近活跃是指创建或者最近发过消息的客户群">
                                <template #reference>
                                    <el-icon class="pop_icon"><question-filled /></el-icon>
                                </template>
                            </el-popover>
                        </div>
                        <div class="item_con">
                            <el-radio-group v-model="form.cust_filter_type" @change="getMembersNum">
                                <el-radio :label="1">全部群主</el-radio>
                                <el-radio :label="2">
                                    按条件筛选群主 &nbsp;
                                    <el-select
                                        v-model="form.user_ids"
                                        popper-class="zw-hide_select_option"
                                        :popper-append-to-body="false"
                                        class="form_item_input"
                                        placeholder="选择员工"
                                        collapse-tags
                                        multiple
                                        :disabled="form.cust_filter_type == 1"
                                        @click="openDepart"
                                        @change="changeDepart">
                                        <el-option
                                            v-for="item in creators"
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id">
                                            {{ item.name }}
                                        </el-option>
                                    </el-select>
                                </el-radio>
                            </el-radio-group>
                            <div class="cus_type_0">
                                预计可触达客户群数<span>{{ customer_num }}</span> 个
                            </div>
                        </div>
                    </div>
                    <!-- 消息内容 -->
                    <div class="list_item mt20">
                        <div class="item_title">
                            <span class="title_icon"></span><span class="should">*</span>消息内容
                            <el-popover
                                placement="top-start"
                                effect="dark"
                                :width="200"
                                trigger="hover"
                                content="注意：每个客户群每天可接收1条群发消息，不限为企业发布的群发还是个人发布的群发。">
                                <template #reference>
                                    <el-icon class="pop_icon"><question-filled /></el-icon>
                                </template>
                            </el-popover>
                        </div>
                        <MaterialContent
                            ref="materialContentRef"
                            :max-num="9"
                            :input-content-tabs="inputContentTabs"
                            :show-material-tabs="showMaterialTabs"
                            :input-content-data="inputContentData"
                            :material-content-data="materialContentData"
                            @change="changeMaterial" />
                    </div>
                    <!-- 群发时间设定 -->
                    <div class="list_item mt20 list_item_none bdb_none">
                        <div class="item_title"><span class="title_icon"></span>群发时间设定</div>
                        <div class="item_con item_time">
                            <el-radio-group v-model="form.sync_wx_type">
                                <el-radio :label="1">立即发送</el-radio>
                                <el-radio :label="2">指定时间发送</el-radio>
                            </el-radio-group>
                            <el-date-picker
                                v-if="form.sync_wx_type == 2"
                                v-model="form.sync_wx_time"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                :disabled-date="disabledDate"
                                type="datetime"
                                placeholder="请选择下发时间" />
                        </div>
                    </div>
                </div>
                <div class="content-right">
                    <div class="pre_title">消息内容预览</div>
                    <PhonePreview ref="phonePreviewRef" />
                </div>
                <!-- 部门人员弹框 -->
                <ZWDepart ref="DepartRef" :type="1" @submit="getDepart" />
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" @click="noticeSend">通知群主发送</el-button>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import ZWDepart from '@/components/ZWDepart.vue';
import { getSetionId, IsNotEmpty, initMaterialData } from '@/utils/utils';
import MaterialContent from '@/components/zw/materialContent/index.vue';
import PhonePreview from '@/components/zw/phonePreview/welcomePhonePreview/materialPreview/index.vue';
import { createGroups, filterChannelCustomerGroup, channelGroupsInfo } from '@/api/channel/index';
import { ElMessage } from 'element-plus';
import router from '@/router';
import dayjs from 'dayjs';

const route = useRoute();
const routerParams = route.query;
const DepartRef = ref(null);
const creators = ref([]);

// 条件参数
const cust_filter_json = ref({});
const customer_num = ref(0);
const materialContentRef = ref<HTMLElement | null>();
const phonePreviewRef = ref<HTMLElement | null>();
const inputContentTabs = ref<Array<number>>([1, 2, 3]); // 配置欢迎语输入框选项
const showMaterialTabs = ref<Array<string>>(['1', '2', '3', '4', '5', '6', '7', '9', '11', '10']); // 配置选择素材组件类型
const inputContentData = ref<string>(''); //  用户存放回显数据  欢迎语输入框
const materialContentData = ref<Array<any>>([]);

const form = reactive({
    title: '',
    cust_filter_type: 1,
    user_ids: [],
    create_time: '',
    content: '',
    sync_wx_type: 1,
    sync_wx_time: ''
});
const materialResult = ref<any>(null);
const changeMaterial = (val: any) => {
    materialResult.value = val;
};

const disabledDate = (date: Date) => {
    return dayjs(date).isBefore(dayjs(), 'day');
};

// //打开新建选择人
const openDepart = () => {
    if (form.cust_filter_type == 1) return;
    DepartRef.value.appDialog.title = '选择员工';
    DepartRef.value.departVisble = true;
    DepartRef.value.selectedMember = creators.value;
};
/**
 * 获取部门成员
 * 不同部门同一个员工，需要先去重
 */
const getDepart = (res: any) => {
    let reduce = [];
    const obj = {};
    reduce = res?.reduce((item: any, next: any) => {
        obj[next.id] ? '' : (obj[next.id] = true && item.push(next));
        return item;
    }, []);
    creators.value = reduce;
    form.user_ids = getSetionId('id', creators.value);
    getChannelCustomerTotal();
};
// // 删除部门成员
const changeDepart = (data: any) => {
    const removeDepart = creators.value.find((item: any) => !data.includes(item.id));
    const arr: any[] = creators.value.filter((item: any) => data.includes(item.id));
    form.user_ids = getSetionId('id', arr);
    creators.value = arr;
    DepartRef.value.removeItem(removeDepart);
    getChannelCustomerTotal();
};
// 重置
const resetForm = () => {
    inputContentData.value = '';
    materialContentData.value = [];
    form.title = '';
    form.cust_filter_type = 1;
    form.user_ids = [];
    form.content = '';
    form.sync_wx_type = 1;
    form.sync_wx_time = '';
    creators.value = [];
    DepartRef.value.removeItem(form.user_ids);
    materialContentRef.value.clearInput();
    materialContentRef.value.clearMaterial();
};

// 预计可触发客户多少人
const getChannelCustomerTotal = () => {
    cust_filter_json.value = {
        work_user: [],
        work_department: []
    };
    const params = {
        work_user: [],
        work_department: []
    };
    // 添加员工
    if (creators.value.length > 0) {
        creators.value.forEach((item: any) => {
            //部门
            if (item.type == 'department') {
                params.work_department.push(item.id);
                cust_filter_json.value.work_department.push({
                    name: item.name,
                    id: item.id
                });
            } else {
                // 成员
                params.work_user.push(item.id);
                cust_filter_json.value.work_user.push({
                    name: item.name,
                    id: item.id
                });
            }
        });
    }
    // 参数至少一个不为空 按条件查询
    const flag = Object.keys(params).some((key: string) => {
        return IsNotEmpty(params[key]);
    });
    if (!flag && form.cust_filter_type == 2) return;
    params.cust_filter_type = form.cust_filter_type;
    filterChannelCustomerGroup(params).then((res: any) => {
        customer_num.value = res.group_num;
    });
};
// 切换人员信息
const getMembersNum = (val: any) => {
    if (val == 1) {
        creators.value = [];
        form.user_ids = [];
        cust_filter_json.value = {
            work_user: [],
            work_department: []
        };
        getChannelCustomerTotal();
        DepartRef.value.removeItem(form.user_ids);
    }
};
// 通知员工发送
const noticeSend = () => {
    delete cust_filter_json.value.cust_filter_type;
    const params = {
        title: form.title,
        cust_filter_type: form.cust_filter_type,
        cust_filter_json: cust_filter_json.value,
        ...materialResult.value,
        sync_wx_type: form.sync_wx_type,
        sync_wx_time: form.sync_wx_time
    };
    if (!form.title) {
        ElMessage.warning('请输入群发标题');
        return;
    }
    if (form.cust_filter_type == 2) {
        // 参数至少一个不为空 按条件查询
        const flag = Object.keys(cust_filter_json.value).some((key: string) => {
            return IsNotEmpty(cust_filter_json.value[key]);
        });
        if (!flag) {
            ElMessage.warning('请选择员工');
            return;
        }
    } else {
        delete params.cust_filter_json;
    }

    if (!params.welcome_info.welcome_text) {
        ElMessage.warning('请输入消息内容');
        return;
    }

    if (form.sync_wx_type == 1) {
        form.sync_wx_time = '';
        delete params.sync_wx_time;
    } else {
        if (!form.sync_wx_time) {
            ElMessage.warning('请选择发送时间');
            return;
        }
    }

    createGroups(params).then((res: any) => {
        ElMessage.success(`创建成功`);
        router.back();
    });
};

/**
 * @description: 初始化回显数据（复制）
 * @return {*}
 */
const initData = async () => {
    if (routerParams?.id) {
        const res: any = await channelGroupsInfo({ send_msg_id: routerParams?.id });
        const { title, cust_filter_type, cust_filter_json, sync_wx_type, sync_wx_time, welcome_info } = res;
        form.title = `${title}副本`;
        // cust_filter_type 客户范围 1-全部客户 2-条件筛选
        form.cust_filter_type = cust_filter_type;
        if (cust_filter_type === 2) {
            cust_filter_json.value = cust_filter_json;
            const { work_user } = cust_filter_json;
            if (work_user?.length) {
                creators.value.splice(0);
                creators.value.push(...work_user);
                const user_ids = work_user.map(item => item.id);
                form.user_ids.splice(0);
                form.user_ids.push(...user_ids);
            }
        }
        // sync_wx_type 群发时间设定 1-立刻发送 2-指定时间发送
        form.sync_wx_type = sync_wx_type;
        if (sync_wx_type === 2) {
            form.sync_wx_time = sync_wx_time;
        }
        if (welcome_info?.welcome_text) inputContentData.value = welcome_info?.welcome_text;
        if (welcome_info?.welcome_material?.length)
            materialContentData.value = initMaterialData(welcome_info?.welcome_material);
    }
};

onMounted(async () => {
    await initData();
    getChannelCustomerTotal();
});
</script>
<style lang="scss" scoped>
.create_content {
    padding: 24px;
    display: flex;

    .content-left {
        flex: 1;
        padding-right: 40px;
        border-right: 1px solid #eee;

        .list_item {
            padding-left: 18px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eaeaea;

            .item_title {
                font-size: 14px;
                line-height: 18px;
                font-family: STHeitiSC-Medium, STHeitiSC;
                font-weight: 500;
                color: #33302d;
                margin-bottom: 16px;

                .should {
                    display: inline-block;
                    color: red;
                    margin-right: 3px;
                }

                .pop_icon {
                    vertical-align: middle;
                    margin-top: -2px;
                    color: #fff;
                    background: #969696;
                    border-radius: 50%;
                }

                .title_icon {
                    display: block;
                    height: 18px;
                    width: 3px;
                    background: #ff6b00;
                    float: left;
                    margin-left: -15px;
                }
            }

            .item_con_input {
                width: 470px;
            }

            .item_con {
                .cus_type_0 {
                    margin-top: 20px;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    font-weight: 300;
                    color: #33302d;

                    span {
                        color: #ff6b00;
                    }
                }

                .form_cus_type {
                    margin-top: 5px;

                    .el-form-item__content {
                        .form_item_input {
                            .el-input__inner {
                                width: 253px !important;
                            }
                        }
                    }

                    .picker_item_date {
                        :deep .el-form-item__content {
                            .el-input__inner {
                                width: 217px !important;
                            }
                        }
                    }
                }

                .input_textarea {
                    width: 100%;

                    :deep(.el-textarea__inner) {
                        height: 170px;
                        background: #f8f8f8;
                        border: 0;
                        box-shadow: none;
                        border-bottom: 1px solid #eaeaea;
                        padding: 5px 0;
                    }
                }
            }

            .item_time {
                display: flex;
                align-items: center;
                gap: 12px;
            }

            .item_message_box {
                background: #f8f8f8;
                border: 1px solid #eaeaea;
                border-radius: 4px;
                width: 580px;
                height: 380px;
                position: relative;

                .simple_fn {
                    margin-top: 5px;
                    display: flex;
                    align-items: center;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    font-weight: 300;
                    color: #33302d;
                    padding-bottom: 6px;
                    border-bottom: 1px solid #eaeaea;

                    .cus_name {
                        margin-left: 18px;
                        color: #ff6b00;
                        cursor: pointer;
                    }

                    .emoj {
                        margin-left: 5px;
                        cursor: pointer;
                    }

                    .sele_text {
                        cursor: pointer;
                    }
                }

                .upload_list_box {
                    overflow: hidden;
                    height: 135px;
                }

                .upload_list {
                    .upload_item {
                        margin-top: 5px;
                        width: 440px;
                        height: 32px;
                        box-sizing: border-box;
                        background: #eaeaea;
                        display: flex;
                        padding: 0 10px 0 14px;
                        align-items: center;

                        .file_icon {
                            width: 20px;
                            height: 20px;
                            margin-right: 7px;
                        }

                        .file_name {
                            width: 375px;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                            overflow: hidden;
                        }

                        .del_icon {
                            width: 10px;
                            height: 10px;
                            cursor: pointer;
                        }
                    }
                }

                .upload_btn {
                    margin-top: 8px;
                    width: 460px;
                    height: 32px;
                    background: #f8f8f8;
                    border: 1px solid #d9d9d9;
                    padding: 0 12px;
                    box-sizing: border-box;
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    font-weight: 300;
                    cursor: pointer;
                    color: #969696;

                    .upload_text {
                        margin-left: 8px;
                    }
                }

                .upload_pop {
                    position: absolute;
                    bottom: 50px;
                    left: -20px;
                    width: 360px;
                    height: 84px;
                    background: #fff;
                    border-radius: 12px;
                    box-shadow: 0 2px 4px 0 rgb(216 216 216 / 50%);
                    display: flex;
                    align-items: center;
                    justify-content: space-around;

                    .item_pop {
                        width: 60px;
                        height: 62px;
                        background: #fff;
                        border-radius: 6px;
                        border: 1px solid #f9f9f9;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        flex-direction: column;
                        cursor: pointer;

                        .item_pop_icon {
                            width: 40px;
                        }

                        .item_pop_name {
                            font-size: 14px;
                            margin-top: 2px;
                            font-family: PingFangSC-Regular, 'PingFang SC';
                            font-weight: 400;
                            color: #1a1918;
                        }
                    }

                    &::after {
                        content: '';
                        position: absolute;
                        bottom: -10px;
                        left: 50%;
                        transform: translate(-50%);
                        width: 0;
                        height: 0;
                        border-left: 10px solid transparent;
                        border-right: 10px solid transparent;
                        border-top: 10px solid #fff;
                    }
                }

                .emoj_box {
                    width: 270px;
                    position: absolute;
                    top: -40px;
                }
            }
        }

        .bdb_none {
            border-bottom: none;
        }

        .btn_form_box {
            margin-top: 12px;
            text-align: right;
        }
    }

    .mt20 {
        margin-top: 20px;
    }

    .ml10 {
        margin-left: 10px;
    }

    .pad12 {
        padding: 0 12px;
    }

    .content-right {
        padding: 24px 24px 0 48px;

        .pre_title {
            margin-bottom: 10px;
            text-align: center;
        }
    }
}

.bottom-btns {
    .btns {
        display: flex;
        align-items: center;
        justify-content: center;
    }
}
</style>
